package de.dopichaj.labrador.index;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * This class models Intervals with associated data.

 * @param <T> the type of the data
 */
public final class IntervalSequence<T> {
    
    public static final class Interval<T> {
        public final int fragmentIdLimit;
        public final T data;
        public Interval(int limit, T data) {
            this.fragmentIdLimit = limit;
            this.data = data;
        }
        @Override
        public String toString() {
            return fragmentIdLimit + "/" + data;
        }
    }
    
    /**
     * The current upper limit of all intervals.
     */
    private int currentMax = Integer.MIN_VALUE;

    /**
     * List of the intervals.
     */
    private final List<Interval<T>> limits = new ArrayList<Interval<T>>();
    
    public IntervalSequence() {
        // add the sentinel
        add(-1, null);
    }
    
    /**
     * Add a new interval. All values &lt;= <code>maxValue</code> that are not
     * in previously added intervals are associated with <code>data</code>.
     * @param maxValue
     *      the upper limit of the interval (inclusive); must be greater than
     *      the previously added upper limits
     * @param data
     *      the data to associate with this interval
     * @throws
     *      IllegalArgumentException if <code>maxValue</code> lies inside a
     *          previously added interval.
     */
    public void add(int maxValue, T data) {
        if (maxValue <= currentMax) {
            throw new IllegalArgumentException("Interval limits must increase (" +
                maxValue + " <= " + currentMax);
        }
        currentMax = maxValue;
        limits.add(new Interval<T>(maxValue, data));
    }

    /**
     * Find the data of the interval that contains <code>value</code>.
     * @param value
     *      the value to search for (must lie in an interval)
     * @return
     *      the data associated with the interval
     * @see #add(int, Object)
     */
    public T findIntervalData(int value) {

        if (value < 0 || value > currentMax) {
            throw new IllegalArgumentException("Value out of range (is " +
                value + ", should be in [0, " + currentMax + "]);");
        }
        
        int l = 1;
        int u = limits.size() - 1;
        while (l < u) {
            
            assert(l >= 1);
            assert(u <= limits.size() - 1);
            
            final int i = (l + u) / 2;
            final int valU = limits.get(i).fragmentIdLimit;
            final int valL = limits.get(i - 1).fragmentIdLimit;
            if (value <= valL) {
                u = i - 1;
            } else if (value > valU) {
                l = i + 1;
            } else {
                return limits.get(i).data;
            }
        }
        assert(value <= limits.get(l).fragmentIdLimit);
        assert(value > limits.get(l - 1).fragmentIdLimit);
        return limits.get(l).data;
    }
    
    /**
     * Group the given list of values by interval.
     * @return
     *  a Map from the data associated with the interval to the values that
     *  lie within that interval.
     * 
     */
    public Map<T, Collection<Integer>> groupByInterval(List<Integer> values) {
        
        if (values.size() == 0) {
            return Collections.emptyMap();
        }
        
        final Map<T, Collection<Integer>> grouped =
            new HashMap<T, Collection<Integer>>();
        int idPos = 0;
        Iterator<Integer> valueIterator = values.iterator();
        int currentValue = valueIterator.next();
        for (Interval<T> interval : limits) {

            // find the IDs for this document
            final int limit = interval.fragmentIdLimit;
            final int startPos = idPos;
            while (currentValue <= limit && valueIterator.hasNext()) {
                currentValue = valueIterator.next();
                idPos++;
            }
            if (currentValue <= limit && !valueIterator.hasNext()) {
                idPos++;
                currentValue = Integer.MAX_VALUE;
            }

            // if there were any matches, record them
            if (idPos > startPos) {
                assert interval.data != null :
                    "Values in illegal interval " + interval + ": " +
                    values.subList(startPos, idPos);
                grouped.put(interval.data, values.subList(startPos, idPos));
            }
        }
        
        return grouped;
    }
    
    public Iterator<Interval<T>> iterator() {
        final Iterator<Interval<T>> iterator = limits.iterator();
        // skip the sentinel
        iterator.next();
        return iterator;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/